import React, {
  ReactElement,
  useCallback,
  useContext,
  useEffect,
  useState
} from 'react';
import { View, Image, ScrollView } from 'react-native';

import styles from './style';
import { avatar, failIcon, score } from '../../../../constant/resource';
import Button from '../../../../components/Button';
import Text from '../../../../components/Text';
import { Store } from '../../reducer';
import { lessonFinished, leaveAllChannel } from '../../actions';
import { ClassApi } from '../../../../api';
import { UserLessonEndInfo } from '../../../../api/class/getLessonEndPage';
import { getUserInfo } from '../../../../store/user';
import Log from '../../../../common/log';
import { clearCoinProgress } from '../../store/coinProgress';

const TAG = 'LiveEnd';

export default (): ReactElement => {
  const [isFetchFailed, setIsFetchFailed] = useState(false);
  const [userGoldCoinNum, setUserGoldCoinNum] = useState<number>(0);
  const [userLessonEndInfoList, setUserLessonEndInfoList] = useState<
    UserLessonEndInfo[]
  >([]);

  const { state } = useContext(Store);
  const { showLiveEnd, lesson } = state;
  const { lessonId } = lesson;

  const getResult = useCallback((): void => {
    if (!showLiveEnd) return;
    ClassApi.getLessonEndPage({ lessonId })
      .then((res): void => {
        if (res.code === 0) {
          setIsFetchFailed(false);
          setUserGoldCoinNum(res.data.userGoldCoinNum);
          setUserLessonEndInfoList(res.data.userLessonEndInfoList);
        } else {
          setIsFetchFailed(true);
        }
      })
      .catch((): void => {
        setIsFetchFailed(true);
      });
  }, [lessonId, showLiveEnd]);

  useEffect((): void => {
    getResult();
  }, [getResult]);

  // 课程结束
  useEffect((): void => {
    if (showLiveEnd) {
      clearCoinProgress();
      lessonFinished();
      leaveAllChannel();
      Log.i(TAG, JSON.stringify({ event: 'showLiveEnd', lessonId }));
    }
  }, [lessonId, showLiveEnd]);

  const { userId } = getUserInfo();
  const myself = userLessonEndInfoList.find(
    (item): boolean => String(item.userId) === userId
  );
  let userList = userLessonEndInfoList.filter(
    (info): boolean => String(info.userId) === userId
  );
  if (myself) {
    userList = [myself, ...userList];
  }
  const myAddCoinNum = myself ? myself.coinChangeNum : 0;

  if (!showLiveEnd) return <View />;

  if (isFetchFailed) {
    return (
      <View style={styles.emptyContainer}>
        <Image source={failIcon} style={styles.icon} />
        <Text style={styles.desc}>网络超时 加载失败</Text>
        <Button
          textStyle={styles.backDesc}
          style={styles.reload}
          text="请重试"
          onPress={(): void => {
            getResult();
          }}
        />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      {userList.length > 0 && <Text style={styles.title}>恭喜完成本节课</Text>}
      <View style={styles.content}>
        <ScrollView
          horizontal
          style={styles.loadStudents}
          contentContainerStyle={styles.students}
          showsHorizontalScrollIndicator={false}
        >
          {userList.map(
            ({ userName, headURL, coinChangeNum }): ReactElement => (
              <View style={styles.student}>
                <Image
                  style={styles.avatar}
                  source={headURL ? { uri: headURL } : avatar}
                />
                <Text style={styles.name} numberOfLines={1}>
                  {userName}
                </Text>
                <View style={styles.studentInfo}>
                  <Image style={styles.coinIcon} source={score} />
                  <Text style={styles.addCoin}>+{coinChangeNum}</Text>
                </View>
              </View>
            )
          )}
        </ScrollView>
      </View>
      <View style={styles.loadMyCoin}>
        <Image style={styles.myCoinIcon} source={score} />
        <Text style={styles.myCoin}>我的金币:{userGoldCoinNum}</Text>
        <Text style={styles.myAddCoin}>+{myAddCoinNum}</Text>
      </View>
    </View>
  );
};
